package cn.com.spic.demo.controller;

import cn.com.spic.demo.api.*;
import cn.com.spic.demo.dto.*;
import cn.com.spic.demo.utils.ExcelExportUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cpipec.demo.spi.EOSServerRestClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 行动项Controller
 */
@RestController
@RequestMapping(value = "/action")
public class ActionProController {

    @Autowired
    private ActionProjectService actionProjectService;

    @Autowired
    private ProgressReportService progressReportService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private SpecialProjectService specialProjectService;

    @Autowired
    private ActionProjectNoteService actionProjectNoteService;

    @Autowired
    private EOSServerRestClient eosServerRestClient;
//    @Autowired
//    private BenchMarService benchMarService;
    /**
     * 获取全部行动项
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/getAllActions" )
    public List<ActionProejctDTO> getAllActions(HttpServletRequest httpServletRequest){
        String actionId = httpServletRequest.getParameter("id");
        return actionProjectService.getActionProDtos(actionId);
    }

//    @PostMapping
//    public ActionProejctDTO save(@RequestBody ActionProejctDTO actionProejctDTO)
//    {
//        ActionProejctDTO dto = actionProjectService.save(actionProejctDTO);
//        dto.setParentProjectId(actionProejctDTO.getParentProjectId());
//            progressReportService.insertProgressReportDtos(dto);
//        return dto;
//    }

    //获取第二级行动项
    @GetMapping(value = "/getActionDetailAndLevelTwoList")
    public List<ActionProejctDTO> getActionDetailAndLevelTwoList(HttpServletRequest httpServletRequest){
        String actionId = httpServletRequest.getParameter("id");
        DecimalFormat df=new DecimalFormat("0.000");
        Calendar cal = Calendar.getInstance();
        List<ActionProejctDTO> dtosLevel2 = actionProjectService.getActionDetailAndLevelList(actionId,"2");
        int nu = 0;
        if(dtosLevel2!=null&&dtosLevel2.size()>0){
            List<ActionProejctDTO>     specialNumbers = actionProjectService.getActionProDtosByNineId(dtosLevel2.get(0).getSpecialId());
            nu = specialNumbers.size();
        }
        assert dtosLevel2 != null;
        for(ActionProejctDTO oneDto:dtosLevel2){
            Integer number1 = progressReportService.countByExample(oneDto.getId(),"1");

            double allDepeRate = 0.0;
            Map<String,String> map = new HashMap<>();
            map.put("def2",oneDto.getId());
            map.put("def3","1");
            map.put("year",String.valueOf(cal.get(Calendar.YEAR)));
            map.put("month",String.valueOf(cal.get(Calendar.MONTH )+1));

            String a = progressReportService.getSumMaxActRateReportdtos(map);
            Double actualFirstDeptRateSum = 0.00;
            Double actualSecDeptRateSum = 0.00;

            if(a!=null &&  !("").equals(a)){
                actualFirstDeptRateSum = Double.parseDouble(a);
            }

            Integer number2 = progressReportService.countByExample(oneDto.getId(),"2");

            Map<String,String> map1 = new HashMap<>();
            map1.put("def2",oneDto.getId());
            map1.put("def3","2");
            map1.put("year",String.valueOf(cal.get(Calendar.YEAR)));
            map1.put("month",String.valueOf(cal.get(Calendar.MONTH )+1));
            String b = progressReportService.getSumMaxActRateReportdtos(map1);
            if(b!=null &&  !("").equals(b)){
                actualSecDeptRateSum = Double.parseDouble(b);
            }
            if(oneDto.getWeight()!=null && number2!=0 && number1!=0){
                allDepeRate = (actualFirstDeptRateSum*Double.parseDouble(oneDto.getWeight())/number1+actualSecDeptRateSum*(1-Double.parseDouble(oneDto.getWeight()))/number2)/nu;
            }else {
                allDepeRate = 0.0;
            }
            oneDto.setTrueactualComRate(df.format(allDepeRate));
        }
        return dtosLevel2;
    }

    /**
     * 获取第三级行动项
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/getActionDetailAndLevelThreeList")
    public List<ActionProejctDTO> getActionDetailAndLevelThreeList(HttpServletRequest httpServletRequest){
        String actionId = httpServletRequest.getParameter("id");
        DecimalFormat df=new DecimalFormat("0.000");
        List<ActionProejctDTO> actionProejctDTO = actionProjectService.getActionProDtos(actionId);   //  获取权重
        List<ActionProejctDTO> action91 = actionProjectService.getActionProDtosByNineId(actionProejctDTO.get(0).getSpecialId());
        Map<String,String> stringMap = new HashMap<>();
        stringMap.put("def2",actionId);
//        List<String> actionIds = progressReportService.getMaxListActionId(stringMap);
        List<ActionProejctDTO> dtosLevel3 = new ArrayList<>();
//        if(actionIds.size()>0){
//            List<ProgressReportDTO> dtos1 = progressReportService.getMaxActRateReportdtos(stringMap);
            dtosLevel3 = actionProjectService.getActionDetailAndLevelList(actionId,"3");
            if(dtosLevel3 != null) {
                dtosLevel3.stream().forEach(oneDto -> {
                    stringMap.put("actionId",oneDto.getId());
                    List<ProgressReportDTO> dtos1 = progressReportService.getMaxActRateReportdtos(stringMap);
                    List<OrgaizationDTO> list = organizationService.getOrgaizations(new String[]{oneDto.getSpicGroupId()});
                    oneDto.setSpicGroupName(list.get(0).getName());
                    dtos1.stream().forEach(dto -> {
                            String weight = null;
                            Map<String,String> map = new HashMap<>();
                            int number = 0 ;
                            if ("1".equals(dto.getDef3())) {
                                if(dto.getDef2().contains(",")){
                                    number = progressReportService.countByExampleByIn("1",dto.getDef2().split(","));
                                }else {
                                    number = progressReportService.countByExample(dto.getDef2(),"1");
                                }
                                weight = actionProejctDTO.get(0).getWeight();
                                oneDto.setTrueactualComRate(df.format(Double.parseDouble(weight)/number*Double.parseDouble(dto.getActualComRate())/action91.size()));
                            } else if ("2".equals(dto.getDef3())) {
                                if(dto.getDef2().contains(",")){
                                    number = progressReportService.countByExampleByIn("2",dto.getDef2().split(","));

                                }else {
                                    number = progressReportService.countByExample(dto.getDef2(),"2");
                                }
                                weight = String.valueOf(1-Double.parseDouble(actionProejctDTO.get(0).getWeight()));
                                oneDto.setTrueactualComRate(df.format(Double.parseDouble(weight)/number*Double.parseDouble(dto.getActualComRate())/action91.size()));

                            }
                    });
                });
            }
//        }

        return dtosLevel3;
    }
    /**
     * 进度查看
     * 根据九大项id获取对应全部行动项
     */
    @GetMapping(value = "/getActionsBySpecialId" )
    public List<ActionProejctDTO> getActionsBySpecialId(HttpServletRequest httpServletRequest) throws ParseException {
        DecimalFormat df=new DecimalFormat("0.00");
        String specialId = httpServletRequest.getParameter("specialId");
        Calendar calendar = Calendar.getInstance();
        //九大项下有多少个行动项数量
        List<ActionProejctDTO> dtos = actionProjectService.getActionProDtosByNineId(specialId);
        for (ActionProejctDTO dto : dtos) {
            List<ActionProejctDTO> dtosLevel2 = actionProjectService.getActionDetailAndLevelList(dto.getId(),"2");
            double allActualRate = 0.0;
            for(ActionProejctDTO oneDto:dtosLevel2){
                int number1 = progressReportService.countByExample(oneDto.getId(),"1");

                double allDepeRate = 0.0;
                Map<String,String> map = new HashMap<>();
                map.put("def2",oneDto.getId());
                map.put("year",String.valueOf(calendar.get(Calendar.YEAR)));
                map.put("month",String.valueOf(calendar.get(Calendar.MONTH) + 1));
                String s = progressReportService.getSumMaxActRateReportdtos(map);
                Double actualFirstDeptRateSum = 0.00;
                if(s!=null &&  !("").equals(s)){
                    actualFirstDeptRateSum = Double.parseDouble(s);
                }
                int number2 = progressReportService.countByExample(oneDto.getId(),"2");

                Map<String,String> map1 = new HashMap<>();
                map1.put("def2",oneDto.getId());
                map1.put("def3","2");
                String s1 = progressReportService.getSumMaxActRateReportdtos(map1);
                Double actualSecDeptRateSum = 0.00;
                if(s1!=null &&  !("").equals(s1)){
                    actualSecDeptRateSum = Double.parseDouble(s1);
                }
                if(oneDto.getWeight()!=null && number1!=0 && number2 !=0){
                    allDepeRate = actualFirstDeptRateSum*Double.parseDouble(oneDto.getWeight())/number1+actualSecDeptRateSum*(1-Double.parseDouble(oneDto.getWeight()))/number2;
                }else {
                    allDepeRate = 0.0;
                }

                    allActualRate = allActualRate+allDepeRate;
            }
            dto.setTrueactualComRate(df.format(allActualRate));

        }
        return dtos;
    }
    // 返回明细项
//    @GetMapping(value = "/getActionDetailByParentId")
//    public List<ActionProejctDTO> getActionDetailByParentId(String parentId) {
//        List<ActionProejctDTO> newActionDto = new ArrayList<>();
//        //明细项
//        List<ActionProejctDTO> list = actionProjectService.getActionDetailByParentId(parentId);
//        //查自己
//        List<ActionProejctDTO> parentDto = actionProjectService.getActionProDtos(parentId);
//        DecimalFormat df=new DecimalFormat("0.00");
//        for (ActionProejctDTO dto : list) {
//            Double actualAllRate = 0.00;
//            //对应明细项 多个单位多个月的最大值
//            List<ProgressReportDTO> actualRates = progressReportService.getMaxActRateReportdtos(dto.getId());
//            //查一个九大项下有多少个行动项
//            Long count = actionProjectService.getCountBySpecialId(parentDto.get(0).getSpecialId());
//            if(actualRates!=null && actualRates.size()>0){
//                    for(ProgressReportDTO a :actualRates){
//                        if(a!=null && !a.equals("")){
//                            Double rate = Double.parseDouble(a.getActualComRate())/(list.size()*count*actualRates.size());
//                            actualAllRate = actualAllRate+rate;
//                        }
//                    }
//                    dto.setActualComRate(df.format((actualAllRate)));
//                }
//            newActionDto.add(dto);
//        }
//        return newActionDto;
//    }
    @GetMapping(value = "/getActionDetailListByParentId")
    public List<ActionProejctDTO> getActionDetailListByParentId(String parentId){
        List<ActionProejctDTO> list = actionProjectService.getActionDetailByParentId(parentId);
        return list;
    }

    @GetMapping(value = "/getActionByUser")
    public List<ActionProejctDTO> getActionByUser(HttpServletRequest request){
        String userId = request.getParameter("userId");
        //        String userCode = (String)CasClientUtils.getLoginedUserAttributes().get("userId");
        String userCode = request.getParameter("userCode");
        String pageSize = request.getParameter("pageSize");
        String pageIndex = request.getParameter("pageIndex");
        EmployeeDTO employeeDTO = employeeService.getEmployeeById(userCode);
        List<ActionProejctDTO> actionList = null;
        List<ActionProejctDTO> trueList = new ArrayList<>();
        Map<String,Object> paramMap = new HashMap<>();
        if(("org").equals(employeeDTO.getOrgCode().split("-"))){   //二级单位
            paramMap.put("orgCode",employeeDTO.getOrgCode());
            paramMap.put("userId",userId);
            paramMap.put("beginNumber",Integer.parseInt(pageIndex)*Integer.parseInt(pageSize));
            paramMap.put("endNumber", Integer.parseInt(pageSize));
            actionList = actionProjectService.getEJDWActionProByUser(paramMap);

        }else{
            paramMap.put("orgCode",employeeDTO.getOrgCode());
            paramMap.put("userId",userId);
            paramMap.put("beginNumber",Integer.parseInt(pageIndex)*Integer.parseInt(pageSize));
            paramMap.put("endNumber", Integer.parseInt(pageSize));
            actionList = actionProjectService.getActionProByUser(paramMap);
        }
        return actionList;
    }

    @PostMapping(value = "/selectActionByAnyCondition")
    public List<SpecialProjectDTO> selectActionByAnyCondition(JSONObject object){
        String askNineName = object.getString("askNineName");
        String askDeptName = object.getString("askDeptName");
        String askOrgName = object.getString("askOrgName");
        List<SpecialProjectDTO> specialProjectDTOs = null;
        if(askNineName==null || ("").equals(askNineName)){
            specialProjectDTOs =  specialProjectService.getAllSpecialProList();
        }else {
            specialProjectDTOs = specialProjectService.getSpecialByName(askNineName);
        }
        for(SpecialProjectDTO dto:specialProjectDTOs){
            List<ActionProejctDTO> actionProejctDTOS91 = actionProjectService.getActionProDtosByNineId(dto.getId());
            for(ActionProejctDTO act91Dto:actionProejctDTOS91) {
                List<String> orgCodes = organizationService.getOrgByLike(askDeptName);
                List<String> actionIds = null;
                if (orgCodes != null && orgCodes.size() > 0) {
                    actionIds = progressReportService.selectActionIdByLike(orgCodes.toArray());
                }
                List<ActionProejctDTO> actionProejct131DTOS = null;
                if (actionIds != null && actionIds.size() > 0) {
                    MoreActionProjectExample example = new MoreActionProjectExample();
                    MoreActionProjectExample.Criteria criteria = example.createCriteria();
                    criteria.andLevelEqualTo("2");
                    criteria.andIdIn(actionIds);
                    actionProejct131DTOS = actionProjectService.selectActionByAnyCondition(example);
                }
                act91Dto.setActionProejctDTOS(actionProejct131DTOS);
                assert actionProejct131DTOS != null;
                for(ActionProejctDTO dto131:actionProejct131DTOS){
                    List<String> org131Codes = null;
                    if (askOrgName==null || ("").equals(askOrgName)){
                        org131Codes =actionProjectService.getAllSecGroupCode();
                    }else {
                        org131Codes= organizationService.getOrgByLike(askOrgName);
                    }
                    List<String> action131Ids = null;
                    List<ActionProejctDTO> actionProejctejdwDTOS = null;

                    if(org131Codes!=null && org131Codes.size()>0){
                        action131Ids = progressReportService.selectActionIdByLike(org131Codes.toArray());
                    }
                    if(action131Ids!=null && action131Ids.size()>0){
                        MoreActionProjectExample example = new MoreActionProjectExample();
                        MoreActionProjectExample.Criteria criteria = example.createCriteria();
                        criteria.andLevelEqualTo("3");
                        criteria.andIdIn(actionIds);
                        actionProejctejdwDTOS = actionProjectService.selectActionByAnyCondition(example);
                    }
                    dto131.setActionProejctDTOS(actionProejctejdwDTOS);
                }
            }
            dto.setActionProejctDTOS(actionProejctDTOS91);
        }
            return specialProjectDTOs;
    }
    @GetMapping(value = "/groupMonthExecution/{year}/{month}")
    public JSONArray groupMonthExecution(@PathVariable String year,@PathVariable String month){
        DecimalFormat df=new DecimalFormat("0.00000");
        JSONObject object = new JSONObject();
        JSONObject object1 = new JSONObject();
        JSONObject object2 = new JSONObject();

        JSONArray array = new JSONArray();
        List<SpecialCountDTO> specialDtos = actionProjectService.getEverySpecilCount();
        BigDecimal[] planComRate = new BigDecimal[specialDtos.size()];
        BigDecimal[] actComRate = new BigDecimal[specialDtos.size()];
        BigDecimal[] planAndAct = new BigDecimal[specialDtos.size()];

        List<SpecialCountDTO> nineDtos = actionProjectService.getEveryNOCount();
        Map<String,String> specialMap =specialDtos.stream().collect(Collectors.toMap(SpecialCountDTO::getId, SpecialCountDTO::getCount, (key1, key2) ->key2));
        Map<String,String> agonineMap =nineDtos.stream().collect(Collectors.toMap(SpecialCountDTO::getId, SpecialCountDTO::getCount, (key1,key2) ->key2));
        Map<String,String> nineMap = new HashMap<>();
        List<AllThreeAndFourActionDTO> allThreeAndFourActionDTOS= null;
        for (Map.Entry<String, String> entry : agonineMap.entrySet()) {
            if (entry.getKey().contains(",")) {
                String[] trueKey = entry.getKey().split(",");
                for (String s : trueKey) {
                    nineMap.put(s, entry.getValue());
                }
            }else {
                nineMap.put(entry.getKey(),entry.getValue());
            }
        }
        for (Map.Entry<String, String> entry : specialMap.entrySet()) {
            BigDecimal planRate = new BigDecimal(0.00);
            BigDecimal actRate = new BigDecimal(0.00);

            List<ThreeActionDTO> dtos = actionProjectService.getThreeAction(entry.getKey());
            for (ThreeActionDTO dto:dtos){
                Map<String,Object> map = new HashMap<>();
                map.put("actionId",dto.getActionId());
                allThreeAndFourActionDTOS = actionProjectService.allThreeAndFourAction(map);
                if(allThreeAndFourActionDTOS!=null && allThreeAndFourActionDTOS.size()>0){
                    for (AllThreeAndFourActionDTO dto1:allThreeAndFourActionDTOS){
                        Double nowPlanRate;
                        Double nowActRate;

//                        YearAndMonthDTO dto2 = progressReportService.getMaxYearAndMonth(dto1.getActionId());
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("year",year);
                        map1.put("month",month);
                        map1.put("actionId",dto1.getActionId());

                        if( dto1.getIdentity().equals("1")){
                            map1.put("def3","1");
                            String sum1 = progressReportService.getThirdSumActRate(map1);
                            Double sum11 = 0.00;
                            if(sum1!=null&&!("").equals(sum1)){
                                sum11 = Double.parseDouble(sum1);
                            }
                            nowPlanRate = Double.parseDouble(dto1.getMonthnumber())/Integer.parseInt(dto1.getSumIdentity())*Double.parseDouble(dto.getWeight());
                            nowActRate = sum11*nowPlanRate/ Double.parseDouble(dto1.getMonthnumber());
                            planRate = planRate.add(new BigDecimal(nowPlanRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));
                            actRate = actRate.add(new BigDecimal(nowActRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));
                            planComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(planRate));
                            actComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate));
                            planAndAct[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate.divide(planRate,5, BigDecimal.ROUND_HALF_UP)));

                        }else {
                            map1.put("def3","2");
                            String sum2 = progressReportService.getThirdSumActRate(map1);
                            Double sum22 = 0.00;
                            if(sum2!=null&&!("").equals(sum2)){
                                sum22 = Double.parseDouble(sum2);
                            }
                            nowPlanRate = Double.parseDouble(dto1.getMonthnumber())/Integer.parseInt(dto1.getSumIdentity())*(1-Double.parseDouble(dto.getWeight()));
                            nowActRate = sum22*nowPlanRate/ Double.parseDouble(dto1.getMonthnumber());
                            planRate = planRate.add(new BigDecimal(nowPlanRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));
                            actRate = actRate.add(new BigDecimal(nowActRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));

                            planComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(planRate));
                            actComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate));
                            planAndAct[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate.divide(planRate,5, BigDecimal.ROUND_HALF_UP)));

                        }
                    }
                }
            }

        }
        object.put("name","计划当月完成进度");
        object.put("data",planComRate);

        object1.put("name","实际当月完成进度");
        object1.put("data",actComRate);

        object2.put("name","计划完成率");
        object2.put("data",planAndAct);
        array.add(object);
        array.add(object1);
        array.add(object2);

        return array;
    }

    /**
     * 集团公司累计进度完成情况
     * @return
     */
    @GetMapping(value = "/allMonthExecution/{year}/{month}")
    public JSONArray allMonthExecution(@PathVariable String year,@PathVariable String month){
        DecimalFormat df=new DecimalFormat("0.00000");
        JSONObject object = new JSONObject();
        JSONObject object1 = new JSONObject();
        JSONObject object2 = new JSONObject();

        JSONArray array = new JSONArray();
        List<SpecialCountDTO> specialDtos = actionProjectService.getEverySpecilCount();
        BigDecimal[] planComRate = new BigDecimal[specialDtos.size()];
        BigDecimal[] actComRate = new BigDecimal[specialDtos.size()];
        BigDecimal[] planAndAct = new BigDecimal[specialDtos.size()];

        List<SpecialCountDTO> nineDtos = actionProjectService.getEveryNOCount();
        Map<String,String> specialMap =specialDtos.stream().collect(Collectors.toMap(SpecialCountDTO::getId, SpecialCountDTO::getCount, (key1, key2) ->key2));
        Map<String,String> agonineMap =nineDtos.stream().collect(Collectors.toMap(SpecialCountDTO::getId, SpecialCountDTO::getCount, (key1,key2) ->key2));
        Map<String,String> nineMap = new HashMap<>();
        List<AllThreeAndFourActionDTO> allThreeAndFourActionDTOS= null;
        for (Map.Entry<String, String> entry : agonineMap.entrySet()) {
            if (entry.getKey().contains(",")) {
                String[] trueKey = entry.getKey().split(",");
                for (String s : trueKey) {
                    nineMap.put(s, entry.getValue());
                }
            }else {
                nineMap.put(entry.getKey(),entry.getValue());
            }
        }
        for (Map.Entry<String, String> entry : specialMap.entrySet()) {
            BigDecimal planRate = new BigDecimal(0.00);
            BigDecimal actRate = new BigDecimal(0.00);

            List<ThreeActionDTO> dtos = actionProjectService.getThreeAction(entry.getKey());
            for (ThreeActionDTO dto:dtos){
                Map<String,Object> map = new HashMap<>();
                map.put("actionId",dto.getActionId());
                allThreeAndFourActionDTOS = actionProjectService.allLJThreeAndFourAction(map);
                if(allThreeAndFourActionDTOS!=null && allThreeAndFourActionDTOS.size()>0){
                    for (AllThreeAndFourActionDTO dto1:allThreeAndFourActionDTOS){
                        Double nowPlanRate = 0.0;
                        Double nowActRate = 0.0;
                        Map<String,String> map1 = new HashMap<>();
                        map1.put("actionId",dto1.getActionId());
                        map1.put("year",year);
                        map1.put("month",month);
                        if( dto1.getIdentity().equals("1")){
                            map1.put("def3","1");
                            String sum1 = progressReportService.getSumMaxActRateReportdtos(map1);
                            nowPlanRate = Double.parseDouble(dto1.getMonthnumber())/Integer.parseInt(dto1.getSumIdentity())*Double.parseDouble(dto.getWeight());
                            nowActRate = Double.parseDouble(sum1)*nowPlanRate/ Double.parseDouble(dto1.getMonthnumber());
                            planRate = planRate.add(new BigDecimal(nowPlanRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));
                            actRate = actRate.add(new BigDecimal(nowActRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));
                            planComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(planRate));
                            actComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate));
                            planAndAct[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate.divide(planRate,5, BigDecimal.ROUND_HALF_UP)));

                        }else {
                            map1.put("def3","2");
                            String sum2 = progressReportService.getSumMaxActRateReportdtos(map1);
                            nowPlanRate = Double.parseDouble(dto1.getMonthnumber())/Integer.parseInt(dto1.getSumIdentity())*(1-Double.parseDouble(dto.getWeight()));
                            nowActRate = Double.parseDouble(sum2)*nowPlanRate/ Double.parseDouble(dto1.getMonthnumber());
                            planRate = planRate.add(new BigDecimal(nowPlanRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));
                            actRate = actRate.add(new BigDecimal(nowActRate/Integer.parseInt(specialMap.get(dto.getSpecialId()))/Integer.parseInt(nineMap.get(dto.getParentActionId()))));

                            planComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(planRate));
                            actComRate[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate));
                            planAndAct[Integer.parseInt(String.valueOf(Integer.parseInt(entry.getKey())-1))] = new BigDecimal(df.format(actRate.divide(planRate,5, BigDecimal.ROUND_HALF_UP)));

                        }
                    }
                }
            }
        }
        object.put("name","累计计划完成进度");
        object.put("data",planComRate);

        object1.put("name","累计实际完成进度");
        object1.put("data",actComRate);

        object2.put("name","累计计划完成率");
        object2.put("data",planAndAct);
        array.add(object);
        array.add(object1);
        array.add(object2);

        return array;
    }
    /**
     * 集团公司对标提升工作逾期项目分析
     */
    @GetMapping(value = "overTimeActionCount/{year}/{month}")
    public void overTimeActionCount(@PathVariable String year,@PathVariable String month){
        JSONArray array = new JSONArray();
        JSONObject object =  new JSONObject();

        String [] specialIds = new String[]{"1","2","3","4","5","6","7","8","9"};
        for (String s :specialIds){
            List<ActionProejctDTO> levelOneDtos = actionProjectService.getActionProDtosByNineId(s);
            for(ActionProejctDTO dto:levelOneDtos){

            }
        }
    }
    /**
     * 二级单位工作进展
     */
    @GetMapping(value = "secGroupWorkExecution/{year}/{month}")
    public  List<SecGroupWorkExecutionDTO> secGroupWorkExecution(@PathVariable String year,@PathVariable String month){
        List<SecGroupWorkExecutionDTO> dtos = new ArrayList<>();
        DecimalFormat df=new DecimalFormat("0.00000");
        List<SecGroupMessageDTO> orgaizationDTOS = organizationService.getSecGroupInFourAction();
        Map<String,Object> map = new HashMap<>();
        String date = year+"-"+month+"-"+"10";
        map.put("date",date);
        map.put("year",year);
        map.put("month",month);
        map.put("level","3");
        for (SecGroupMessageDTO dto:orgaizationDTOS){
            SecGroupWorkExecutionDTO truedto = new SecGroupWorkExecutionDTO();
            List<SecGroupWorkComDTO> dtoList = null;
            map.put("dept",dto.getCode());
            truedto.setGroupName(dto.getName());
            truedto.setGroupCode(dto.getCode());
            truedto.setAllActionNumber(dto.getActionAllNumber());
            SecGroupMaxMinAndAllDTO dto1 = actionProjectService.getSecGroupMaxMinAndAll("3");
            Double d  = 0.1*(Integer.parseInt(dto1.getAllNumber())-Integer.parseInt(dto1.getMinNumber()))/(Integer.parseInt(dto1.getAllNumber())-Integer.parseInt(dto1.getMaxNumber()));
            String rate = "0";
            for (int i = 0;i<2;i++){
                map.put("isComplete",i);
                dtoList =actionProjectService.secGroupWorkExecution(map);
                if(i==0){
                    truedto.setOverActionNumber(String.valueOf(dtoList.size()));
                }else {
                    truedto.setComActionNumber(String.valueOf(dtoList.size()));
                }
                rate = "0";
            }
            if(dtoList.size() > 0){
                rate = dtoList.get(0).getRate();
            }
            truedto.setComRate(rate);
            truedto.setScore(df.format(new BigDecimal(rate).multiply(new BigDecimal("0.9")).add(new BigDecimal(d))));
            dtos.add(truedto);

        }
        /**
         * 排序
         */
        Collections.sort(dtos, new Comparator<SecGroupWorkExecutionDTO>() {
            @Override
            public int compare(SecGroupWorkExecutionDTO o1, SecGroupWorkExecutionDTO o2) {
                return o2.getScore().compareTo(o1.getScore());
            }
        });
        return dtos;
    }

    /**
     * 获取二级单位行动项数据
     * @param  code :二级单位/部门编码
     *             identity ：0二级单位 1部门
     * @return
     */
    @GetMapping( value = "getActionsFromOrg/{code}/{identity}")
    public List<DeptAndOrgActionDTO> getActionsFromOrgDept(@PathVariable String code, @PathVariable String identity){
        List<DeptAndOrgActionDTO> dtos = null;
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        map.put("identity",identity);
        /**
         * identity 0 : 二级单位
         * identity 1 : 集团部门
         */
        if(identity.equals("0")){
            dtos = actionProjectService.getdeptAndOrgAction(map);
        }else{
            dtos = actionProjectService.getdeptAndOrgAction(map);
            List<OrgaizationDTO> spicFirstPos = null;
            List<OrgaizationDTO> spicSecPos = null;
            for(DeptAndOrgActionDTO dto:dtos) {
                if(dto.getFirstDept()!=null && dto.getFirstDept().split(",").length>0){
                    spicFirstPos = organizationService.getOrgaizations(dto.getFirstDept().split(","));
                }
                if(dto.getSecDept()!=null && dto.getSecDept().split(",").length>0){
                    spicSecPos = organizationService.getOrgaizations(dto.getSecDept().split(","));
                }
                String firstName = "";
                String secName = "";
                if(spicFirstPos!=null && spicFirstPos.size()>0){
                    for (int f = 0; f < spicFirstPos.size(); f++) {
                        String aaa = "";
                        if (f == spicFirstPos.size() - 1) {
                            aaa = spicFirstPos.get(f).getName();
                        } else {
                            aaa = spicFirstPos.get(f).getName().concat(",");
                        }
                        firstName = firstName.concat(aaa);
                    }
                }
                if(spicSecPos!=null && spicSecPos.size()>0){
                    for (int s = 0; s < spicSecPos.size(); s++) {
                        String aaa = "";
                        if (s == spicSecPos.size() - 1) {
                            aaa = spicSecPos.get(s).getName();
                        } else {
                            aaa = spicSecPos.get(s).getName().concat(",");
                        }
                        secName = secName.concat(aaa);
                    }
                }
                dto.setFirstDept(firstName);
                dto.setSecDept(secName);
            }
        }
        return dtos;
    }
    /**
     * 获取集团部门下二级单位行动项信息
     * @param   parentActionId:部门行动项
     * @return
     */
    @GetMapping(value = "getDeptDownAction/{parentActionId}")
    public List<DeptAndOrgActionDTO> getDeptDownAction(@PathVariable String parentActionId) throws ParseException {
        Map<String,String> map = new HashMap<>();
        map.put("code",parentActionId);
        map.put("identity","2");
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        List<DeptAndOrgActionDTO> dtos = null;
        DecimalFormat df=new DecimalFormat("00.00");
        dtos = actionProjectService.getdeptAndOrgAction(map);
        for(DeptAndOrgActionDTO deptAndOrgActionDTO:dtos){
            deptAndOrgActionDTO.setActualComRate(df.format((Double.parseDouble(deptAndOrgActionDTO.getActualComRate())*100))+"%");
            deptAndOrgActionDTO.setJhwcl(df.format((Double.parseDouble(deptAndOrgActionDTO.getJhwcl())*100))+"%");
        }
        return dtos;
    }
    private static String subMonth(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dt = sdf.parse(date);

        Calendar rightNow = Calendar.getInstance();

        rightNow.setTime(dt);

        rightNow.add(Calendar.MONTH, -1);
        Date dt1 = rightNow.getTime();

        String reStr = sdf.format(dt1);

        return reStr;
    }
    /**
     * 修改行动项数据
     */
    @PostMapping(value = "updateActionMessage")
    public JSONObject updateActionMessage(@RequestBody ActionProejctDTO actionProejctDTO){
        JSONObject rtnMessage = new JSONObject();
        if(actionProejctDTO!=null){
            int a = actionProjectService.updateByExampleSelective(actionProejctDTO);
            if(a!=0){
                ActionProjectNoteDTO dto = new ActionProjectNoteDTO();
                BeanUtils.copyProperties(actionProejctDTO,dto);
                dto.setCreatorId(getUserCode());
                actionProjectNoteService.saveActionProjectNote(dto);
                rtnMessage.put("code","0");
                rtnMessage.put("message","修改成功");
            }else {
                rtnMessage.put("code","1");
                rtnMessage.put("message","修改失败");
            }
        }
        return rtnMessage;
    }
    private String getUserCode(){
        JSON json = eosServerRestClient.getCurrentUser();
        JSONObject object = JSONObject.parseObject(json.toJSONString());
        return object.getString("username");
    }

    /**
     * 判断是否可以修改行动项 0可1不可
     * @param orgCode
     * @return
     */
    @GetMapping(value = "judgeIdentity/{orgCode}")
    public JSONObject judgeIdentity(@PathVariable String orgCode){
        JSONObject object = new JSONObject();

        EmployeeDTO employeeDTO = employeeService.getEmployeeById(getUserCode());
        if(orgCode!=null && orgCode.equals(employeeDTO.getOrgCode()) && "1".equals(employeeDTO.getProfessional())){
            object.put("isUpdate","0");
        }else {
            object.put("isUpdate","1");
        }
        return object;
    }

    @GetMapping(value = "exportExcelByBussines/{type}/{code}")
    public void exportExcelByBussines(@PathVariable String type, @PathVariable String code, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String,String> paramType = new HashMap<>();
        paramType.put("identity",type);
        paramType.put("code",code);
        List<ExportExcelDTO> dtos = actionProjectService.exportExcelLists(paramType);
        List<Map> maps = new ArrayList<Map>();
        for(ExportExcelDTO dto:dtos){
            String lastNewNowMessage = progressReportService.getLastestNowMessage(dto.getActionId());
            dto.setNowMessage(lastNewNowMessage);
        }
        if(type.equals("0")){
            for(ExportExcelDTO dto:dtos){
                Map<Object, Object> stringStringMap = new HashMap<>();
                stringStringMap.put("def2", dto.getDef2());
                stringStringMap.put("actionName", dto.getActionName());
                stringStringMap.put("benchmarkFild", dto.getBenchmarkFild());
                stringStringMap.put("benchmarkObj", dto.getBenchmarkObj());
                stringStringMap.put("questionShow", dto.getQuestionShow());
                stringStringMap.put("uoGoal", dto.getUoGoal());
                stringStringMap.put("mainMeasure", dto.getMainMeasure());
                stringStringMap.put("achievementResult", dto.getAchievementResult());
                stringStringMap.put("endTime", dto.getEndTime());
                stringStringMap.put("nowMessage", dto.getNowMessage());
                stringStringMap.put("firstDept", dto.getFirstDept());
                stringStringMap.put("secDept", dto.getSecDept());
                stringStringMap.put("groupId", dto.getGroupId());
                stringStringMap.put("groupEndTime", dto.getGroupEndTime());
                stringStringMap.put("specialName", actionProjectService.getGroupConcatSpecialName(dto.getActionId()));
                stringStringMap.put("uplevelCode", dto.getUplevelCode());
                stringStringMap.put("uplevelTime", dto.getUplevelTime());
                maps.add(stringStringMap);
            }
            if (maps != null && maps.size() > 0) {
                StringBuffer companyName = new StringBuffer();
                companyName.append(organizationService.getOrgaizations(new String[]{code}).get(0).getName());
                companyName.append("对标提升工作清单");
                String sheetTitle = companyName.toString();
                String title[] = {"序号", "行动项&重点任务", "对标领域", "对标对象", "问题表现", "提升目标", "具体措施", "成果形式",
                        "时间节点", "进展情况", "牵头单位", "配合单位","对应集团公司对标提升工作清单序号","集团公司清单节点时间","专项任务名称","专项对标清单序号","专项对标提升清单节点时间"};
                String[] properties = new String[]{"def2", "actionName", "benchmarkFild", "benchmarkObj",
                        "questionShow", "uoGoal", "mainMeasure", "achievementResult",
                        "endTime", "nowMessage", "firstDept", "secDept","groupId","groupEndTime",
                        "specialName","uplevelCode","uplevelTime"
                };  // 查询对应的;字段
                ExcelExportUtil excelExport2 = new ExcelExportUtil();
                excelExport2.setData(maps);
                excelExport2.setHeardKey(properties);
                excelExport2.setFontSize(14);
                excelExport2.setSheetName(sheetTitle);
                excelExport2.setTitle(sheetTitle);
                excelExport2.setHeardList(title);
                excelExport2.exportExport(request, response, companyName.toString());
            }
        }else if(type.equals("1")){
            for(ExportExcelDTO dto:dtos){

                List<OrgaizationDTO> spicFirstPos = null;
                List<OrgaizationDTO> spicSecPos = null;
                StringBuffer firstName = new StringBuffer();
                StringBuffer secName = new StringBuffer();
                if(dto.getFirstDept()!=null){
                    spicFirstPos = organizationService.getOrgaizations(dto.getFirstDept().split(","));
                }
                if(dto.getSecDept()!=null){
                    spicSecPos = organizationService.getOrgaizations(dto.getSecDept().split(","));
                }
                for(int f=0;f<spicFirstPos.size();f++){
                    String aaa = "";
                    if(f==spicFirstPos.size()-1){
                        aaa = spicFirstPos.get(f).getName();
                    }else{
                        aaa = spicFirstPos.get(f).getName().concat(",");
                    }
                    firstName.append(aaa);
                }
                for(int s=0;s<spicSecPos.size();s++){
                    String aaa = "";
                    if(s==spicSecPos.size()-1){
                        aaa = spicSecPos.get(s).getName();
                    }else{
                        aaa = spicSecPos.get(s).getName().concat(",");
                    }
                    secName.append(aaa);
                }
                Map<Object, Object> stringStringMap = new HashMap<>();
                stringStringMap.put("def2", dto.getDef2());
                stringStringMap.put("actionName", dto.getActionName());
                stringStringMap.put("benchmarkFild", dto.getBenchmarkFild());
                stringStringMap.put("benchmarkObj", dto.getBenchmarkObj());
                stringStringMap.put("questionShow", dto.getQuestionShow());
                stringStringMap.put("uoGoal", dto.getUoGoal());
                stringStringMap.put("mainMeasure", dto.getMainMeasure());
                stringStringMap.put("achievementResult", dto.getAchievementResult());
                stringStringMap.put("endTime", dto.getEndTime());
                stringStringMap.put("nowMessage", dto.getNowMessage());
                stringStringMap.put("firstDept", firstName);
                stringStringMap.put("secDept", secName);
                stringStringMap.put("uplevelCode", dto.getUplevelCode());
                stringStringMap.put("uplevelTime", dto.getUplevelTime());
                maps.add(stringStringMap);
            }
            if (maps != null && maps.size() > 0) {
                StringBuffer companyName = new StringBuffer();
                companyName.append(organizationService.getOrgaizations(new String[]{code}).get(0).getName());
                companyName.append("对标提升工作清单");
                String sheetTitle = companyName.toString();
                String title[] = {"序号", "行动项&重点任务", "对标领域", "对标对象", "问题表现", "提升目标", "具体措施", "成果形式",
                        "时间节点", "进展情况", "牵头单位", "配合单位","对应集团公司对标提升工作清单序号","集团公司清单节点时间"};
                String[] properties = new String[]{"def2", "actionName", "benchmarkFild", "benchmarkObj",
                        "questionShow", "uoGoal", "mainMeasure", "achievementResult",
                        "endTime", "nowMessage", "firstDept", "secDept","uplevelCode","uplevelTime"
                };  // 查询对应的;字段
                ExcelExportUtil excelExport2 = new ExcelExportUtil();
                excelExport2.setData(maps);
                excelExport2.setHeardKey(properties);
                excelExport2.setFontSize(14);
                excelExport2.setSheetName(sheetTitle);
                excelExport2.setTitle(sheetTitle);
                excelExport2.setHeardList(title);
                excelExport2.exportExport(request, response, companyName.toString());
            }
        }
    }
}
